import {
  getSysUserRoleList,
  getSysUserDeptsList,
  getSysUserPageList,
  getSysUserDetail,
  addSysUserDetail,
  editSysUserDetail,
  editSysUserPassword,
  editSysUserRoles,
  editSysUserStatus,
  delSysUserDetail,
  batchDelSysUserDetail
} from "@/api/system/user";
import { reactive, ref } from "vue";
import { arrayToTree } from "@/utils/truncate";
import type { PlusPageInstance, RecordType } from "plus-pro-components";

// 空数据提示（错误提示）
export const tableEmptyText = ref("");

// 页面组件
export const plusPageRef = ref<PlusPageInstance | null>();

// 状态参数
const state = reactive({
  deptsCache: [],
  deptsCacheInit: false,
  rolesCache: [],
  rolesCacheInit: false
});

type ParentOption = {
  /**
   * 选项类型
   */
  type: "depts" | "roles";
  /**
   * 是否关闭缓存
   */
  disableCache?: boolean;
};

const request = {
  event: {
    /**
     * 列表页面初始化成功时调用
     * 如果开启了 KeepAlive，会在激活后再次调用
     *
     * @param keepAlive 本次调用是否为 keepAlive 激活调用
     * @returns
     */
    onPageShow: async (keepAlive: boolean): Promise<void> => {
      if (keepAlive) {
        plusPageRef.value?.getList();
      }
      await request.get.options({ type: "depts", disableCache: true });
      await request.get.options({ type: "roles", disableCache: true });
    }
  },
  get: {
    /**
     * 获取选项
     *
     * @param options 配置信息
     * @returns
     */
    options: async (options: ParentOption) => {
      switch (options.type) {
        case "depts":
          // 部门
          if (!options.disableCache && state.deptsCacheInit) {
            return state.deptsCache;
          }
          const deptsRes = (await getSysUserDeptsList()).data;
          const deptsList = arrayToTree(deptsRes, {
            transform: item => {
              return {
                value: item.id,
                label: item.deptName
              };
            }
          });
          state.deptsCache = deptsList;
          state.deptsCacheInit = true;
          return deptsList;
        case "roles":
          // 角色
          if (!options.disableCache && state.rolesCacheInit) {
            return state.rolesCache;
          }
          const rolesRes = (await getSysUserRoleList()).data;
          const rolesList = rolesRes.map(item => ({
            value: item.id,
            label: item.roleName
          }));
          state.rolesCache = rolesList;
          state.rolesCacheInit = true;
          return rolesList;
      }
    },
    /**
     * 获取树形列表
     *
     * @param params 请求参数
     * @returns
     */
    treeList: async (params: RecordType) => {
      try {
        if (params.depts) {
          params.deptId = params.depts[params.depts.length - 1];
          delete params.depts;
        }
        const res = await getSysUserPageList(params);
        tableEmptyText.value = "资料暂无";
        return {
          data: arrayToTree(res.data.list),
          total: res.data.total
        };
      } catch (error) {
        tableEmptyText.value = error.message;
      }
    },
    /**
     * 获取详情
     *
     * @param id 请求ID
     * @returns
     */
    detail: async (id: Id) => {
      return (await getSysUserDetail(id)).data;
    }
  },
  post: {
    /**
     * 新增信息
     *
     * @param data 请求参数
     * @returns
     */
    create: async (data: object) => {
      const res = await addSysUserDetail(data);
      return { id: res.data.id };
    }
  },
  put: {
    /**
     * 更新信息
     *
     * @param id 请求ID
     * @param data 请求参数
     */
    update: async (id: Id, data: object) => {
      await editSysUserDetail(id, data);
    },
    /**
     * 更新状态
     *
     * @param id 请求ID
     * @param status 设置的状态（布尔）
     * @returns
     */
    setStatus: async (id: Id, status: boolean) => {
      await editSysUserStatus(id, {
        status
      });
    },
    /**
     * 更新密码
     *
     * @param id 请求ID
     * @param data 请求参数
     * @returns
     */
    setPassword: async (id: Id, data: object) => {
      await editSysUserPassword(id, data);
    },
    /**
     * 更新角色
     *
     * @param id 请求ID
     * @param data 请求参数
     * @returns
     */
    setRoles: async (id: Id, data: object) => {
      await editSysUserRoles(id, data);
    }
  },
  delete: {
    /**
     * 删除信息
     *
     * @param id 请求ID
     */
    remove: async (id: Id) => {
      await delSysUserDetail(id);
    },
    /**
     * 批量删除信息
     *
     * @param ids 指定的ID
     */
    batch: async (ids: Id[]) => {
      await batchDelSysUserDetail({
        ids
      });
    }
  }
};

export default request;
